<template>
  <el-dialog
    v-model="isVisitPlanItem"
    :title="visitPlanItemDialogTitle"
    width="1200"
    top="50px"
    body-class="QR-code-dialog-body"
   
  >
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      v-if="isVisitPlanItem"
     
    >
      <template #menu-left>
        <!-- <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.visitPlanItem_delete"
          @click="handleDelete"
          >删 除
        </el-button>
        <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          >导 出
        </el-button> -->
      </template>
    </avue-crud>
  </el-dialog>
</template>

<script setup>
import { getList, getDetail, add, update, remove } from '@/api/visitplanitem/visitPlanItem';
import option from '@/option/visitplanitem/visitPlanItem';
import { mapGetters } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import website from '@/config/website';
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const crud = ref(null);
const store = useStore();
const routerQuery = ref({});
routerQuery.value = route.query;

const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
let options = reactive(option);
const data = ref([]);

let isVisitPlanItem = ref(false);
let visitPlanItemDialogTitle = ref('');
let sendFollowObj = ref({});

const open =  (val, isEdit) => {
  sendFollowObj.value = val;
  isVisitPlanItem.value = true;
  visitPlanItemDialogTitle.value = val.name + '随访计划-详情';

  onLoad(page.value);
     if (!isEdit) {
      options.menu = false;
      options.addBtn = false
  } else {
      options.menu = true;
      options.addBtn = true;
  }
  
};
defineExpose({
  open,
 
});

onMounted(() => {
   
 
    
  initOptions();
});

const initOptions = () => {
  options.menu = true;
  options.addBtn = true;
  if (routerQuery.value.trialId) {
    options.menu = false;
    options.addBtn = false;
  }
};

// permissionList 计算属性
const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
  // addBtn: validData(permission.value.visitPlanItem_add, false),
  // viewBtn: validData(permission.value.visitPlanItem_add, false),
  // delBtn: validData(permission.value.visitPlanItem_add, false),
  // editBtn: validData(permission.value.visitPlanItem_add, false),
}));
// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});

const rowSave = (row, done, loading) => {
  row.smsNotice = '0';
  row.emailNotice = '0';
  if (row.noticeType instanceof Array) {
    row.noticeType = row.noticeType.join(',');
  }
  if (row.intervalArr.length != 0) {
    row.intervalArr = row.intervalArr.map(item => `${item.day}:${item.select}`).join(',');
    // delete row.intervalArr;
  }
  if (row.noticeTime instanceof Array) {
    row.noticeTime = row.noticeTime.join(',');
  }
  row.plan = sendFollowObj.value.id;
  delete row.checkbox;
  delete row.divider;
  add(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  row.plan = sendFollowObj.value.id;
  console.log('11111');
  if (row.noticeTime instanceof Array) {
    row.noticeTime = row.noticeTime.join(',');
  }
  row.smsNotice = '0';
  row.emailNotice = '0';
  console.log('222222');
  if (row.checkbox.length != 0) {
    if (row.checkbox.includes('0')) {
      row.smsNotice = '1';
    }
    if (row.checkbox.includes('1')) {
      row.emailNotice = '1';
    }
  }
  console.log('333333');
  delete row.intervalArr;
  delete row.checkbox;
  delete row.divider;
  console.log('44444');
  update(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleExport = () => {
  const downloadUrl = `/blade-visitplanitem/visitPlanItem/export-visitPlanItem?${
    website.tokenHeader
  }=${getToken()}`;
  const { name } = query.value;
  let values = {
    name_: name,
  };

  ElMessageBox.confirm('是否导出数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    NProgress.start();
    exportBlob(downloadUrl, values).then(res => {
      downloadXls(res.data, `疾病管理${dateNow()}.xlsx`);
      NProgress.done();
    });
  });
};

const beforeOpen = (done, type) => {
  if (['add'].includes(type)) {
    form.value.intervalArr = [{ day: 1, select: '1' }];
  }
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};

const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};

const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    ...params,
    plan: sendFollowObj.value.id,
  };
  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    data.value.forEach(item => {
      if (item.smsNotice === '1' && item.emailNotice === '1') {
        item.checkbox = ['0', '1'];
      } else if (item.smsNotice === '1' && item.emailNotice === '0') {
        item.checkbox = ['0'];
      } else if (item.smsNotice === '0' && item.emailNotice === '1') {
        item.checkbox = ['1'];
      } else {
        item.checkbox = [];
      }
    });
    loading.value = false;
    selectionClear();
  });
};
</script>

<style></style>
